<template>
  <div class="material-management">
    <div class="header">
      <h2>物料管理</h2>
      <div class="subtitle">管理和跟踪所有物料库存、状态和详情</div>
      <el-button type="primary" class="add-button" @click="handleAdd">添加物料</el-button>
    </div>
    
    <!-- 搜索过滤区域 -->
    <div class="filter-section">
      <el-input
        v-model="searchKeyword"
        placeholder="输入物料名称"
        class="search-input"
      />
      <el-select v-model="selectedCategory" placeholder="物料类别" clearable>
        <el-option
          v-for="item in categories"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-select v-model="selectedStatus" placeholder="库存状态" clearable>
        <el-option
          v-for="item in statusOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-button type="primary" @click="handleSearch">筛选</el-button>
    </div>

    <!-- 统计卡片区域 -->
    <div class="statistics-cards">
      <el-card class="stat-card">
        <div class="stat-title">总物料种类</div>
        <div class="stat-amount">{{ statisticsData.total.count }}</div>
        <div class="stat-change increase">{{ statisticsData.total.change > 0 ? '↑' + statisticsData.total.change + '% 较昨日' : '↓' + (-statisticsData.total.change) + '% 较昨日' }}</div>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-title">低库存物料</div>
        <div class="stat-amount">{{ statisticsData.lowStock.count }}</div>
        <div class="stat-change decrease">{{ statisticsData.lowStock.change > 0 ? '↑' + statisticsData.lowStock.change + '% 较昨日' : '↓' + (-statisticsData.lowStock.change) + '% 较昨日' }}</div>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-title">今日入库</div>
        <div class="stat-amount">{{ statisticsData.todayIn.count }}</div>
        <div class="stat-change increase">{{ statisticsData.todayIn.change > 0 ? '↑' + statisticsData.todayIn.change + '% 较昨日' : '↓' + (-statisticsData.todayIn.change) + '% 较昨日' }}</div>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-title">今日出库</div>
        <div class="stat-amount">{{ statisticsData.todayOut.count }}</div>
        <div class="stat-change decrease">{{ statisticsData.todayOut.change > 0 ? '↑' + statisticsData.todayOut.change + '% 较昨日' : '↓' + (-statisticsData.todayOut.change) + '% 较昨日' }}</div>
      </el-card>
    </div>

    <!-- 物料列表表格 -->
    <el-table :data="materialList" stripe style="width: 100%" v-loading="loading">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="name" label="物料名称" />
      <el-table-column prop="code" label="物料编码" />
      <el-table-column prop="spec" label="规格型号" />
      <el-table-column prop="category" label="类别" />
      <el-table-column prop="stock" label="库存数量" />
      <el-table-column prop="status" label="库存状态">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="最近更新" />
      <el-table-column fixed="right" label="操作" width="120">
        <template #default="scope">
          <el-button-group>
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" @click="handleDelete(scope.row)" type="danger">删除</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <span class="total-info">Total {{ total }} {{ pageSize }}/page</span>
      <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        layout="prev, pager, next"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 添加/编辑物料对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加物料' : '编辑物料'"
      width="500px"
    >
      <el-form :model="materialForm" label-width="100px">
        <el-form-item label="物料名称">
          <el-input v-model="materialForm.name" />
        </el-form-item>
        <el-form-item label="物料编码">
          <el-input v-model="materialForm.code" />
        </el-form-item>
        <el-form-item label="规格型号">
          <el-input v-model="materialForm.spec" />
        </el-form-item>
        <el-form-item label="类别">
          <el-select v-model="materialForm.category" placeholder="选择类别">
            <el-option
              v-for="item in categories"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="库存数量">
          <el-input-number v-model="materialForm.stock" :min="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { 
  getStatistics, 
  getMaterialList,
  createMaterial,
  updateMaterial,
  deleteMaterial,
  getCategoryList
} from '@/api/material'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'MaterialManagement',
  setup() {
    const searchKeyword = ref('')
    const selectedCategory = ref('')
    const selectedStatus = ref('')
    const currentPage = ref(1)
    const pageSize = ref(5)
    const total = ref(0)
    const dialogVisible = ref(false)
    const dialogType = ref('add')
    const loading = ref(false)
    const categories = ref([])
    const statisticsData = ref({
      total: { count: 0, change: 0 },
      lowStock: { count: 0, change: 0 },
      todayIn: { count: 0, change: 0 },
      todayOut: { count: 0, change: 0 }
    })

    const statusOptions = [
      { value: 'normal', label: '正常' },
      { value: 'low', label: '低库存' },
      { value: 'stockout', label: '缺货' }
    ]

    const materialList = ref([])
    const materialForm = ref({
      name: '',
      code: '',
      spec: '',
      category: '',
      stock: 0
    })

    // 获取统计数据
    const fetchStatistics = async () => {
      try {
        const response = await getStatistics()
        statisticsData.value = response.data
      } catch (error) {
        ElMessage.error('获取统计数据失败')
      }
    }

    // 获取物料列表
    const fetchMaterialList = async () => {
      loading.value = true
      try {
        const response = await getMaterialList({
          keyword: searchKeyword.value,
          category: selectedCategory.value,
          status: selectedStatus.value,
          page: currentPage.value,
          pageSize: pageSize.value
        })
        materialList.value = response.data.list
        total.value = response.data.total
      } catch (error) {
        ElMessage.error('获取物料列表失败')
      } finally {
        loading.value = false
      }
    }

    // 获取物料类别
    const fetchCategories = async () => {
      try {
        const response = await getCategoryList()
        categories.value = response.data.map(item => ({
          value: item.id,
          label: item.name
        }))
      } catch (error) {
        ElMessage.error('获取物料类别失败')
      }
    }

    onMounted(() => {
      fetchStatistics()
      fetchMaterialList()
      fetchCategories()
    })

    const getStatusType = (status) => {
      switch (status) {
        case '正常':
          return 'success'
        case '低库存':
          return 'warning'
        case '缺货':
          return 'danger'
        default:
          return 'info'
      }
    }

    const handleSearch = () => {
      currentPage.value = 1
      fetchMaterialList()
    }

    const handlePageChange = (page) => {
      currentPage.value = page
      fetchMaterialList()
    }

    const handleAdd = () => {
      dialogType.value = 'add'
      materialForm.value = {
        name: '',
        code: '',
        spec: '',
        category: '',
        stock: 0
      }
      dialogVisible.value = true
    }

    const handleEdit = (row) => {
      dialogType.value = 'edit'
      materialForm.value = { ...row }
      dialogVisible.value = true
    }

    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm('确认删除该物料吗？', '提示', {
          type: 'warning'
        })
        await deleteMaterial(row.id)
        ElMessage.success('删除成功')
        fetchMaterialList()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }

    const handleSave = async () => {
      try {
        if (dialogType.value === 'add') {
          await createMaterial(materialForm.value)
          ElMessage.success('添加成功')
        } else {
          await updateMaterial(materialForm.value.id, materialForm.value)
          ElMessage.success('更新成功')
        }
        dialogVisible.value = false
        fetchMaterialList()
      } catch (error) {
        ElMessage.error(dialogType.value === 'add' ? '添加失败' : '更新失败')
      }
    }

    return {
      searchKeyword,
      selectedCategory,
      selectedStatus,
      categories,
      statusOptions,
      materialList,
      currentPage,
      pageSize,
      total,
      dialogVisible,
      dialogType,
      materialForm,
      loading,
      statisticsData,
      getStatusType,
      handleSearch,
      handlePageChange,
      handleAdd,
      handleEdit,
      handleDelete,
      handleSave
    }
  }
}
</script>

<style scoped>
.material-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.subtitle {
  color: #666;
  margin-top: 8px;
}

.filter-section {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.search-input {
  width: 200px;
}

.statistics-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  padding: 20px;
}

.stat-title {
  color: #666;
  font-size: 14px;
}

.stat-amount {
  font-size: 24px;
  font-weight: bold;
  margin: 10px 0;
}

.stat-change {
  font-size: 12px;
}

.increase {
  color: #67C23A;
}

.decrease {
  color: #F56C6C;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.total-info {
  color: #666;
}
</style> 